package bgate.connector;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import java.util.Vector;

/**
 *
 * @author QuanDD
 */
public class ConnectionHandler{// implements IConnectionHandler
    protected PrintStream _outToSlave;
    protected DataInputStream _inFromSlave;
    protected Socket _socket;    
    protected ReaderThread _reader;
    public WriterThread _writer;
    protected DataTransfer _parent;
    public Vector _outQueue;

    public ConnectionHandler(Socket s, DataTransfer parent) throws IOException {
        _socket = s;
        _parent = parent;
        _outQueue = _parent.outQueue;
        _outToSlave = new PrintStream(s.getOutputStream());
        _inFromSlave = new DataInputStream(s.getInputStream());
        
        _reader = new ReaderThread(_inFromSlave, this);
        _reader.start();
        _writer = new WriterThread(_outToSlave);
        
        _parent.writeThread = _writer;
        _parent.threadPool.putTask(_writer);

    }
/*
    public void setListener(IConnectionListener listener) {
        _listener = listener;
        _reader.setListener(listener);
        _reader.start();
    }
*/
    public void sendMessage(String message) {
        _writer.queueMessage(message);
    }
    /*
    public void sendImmediately(String message) {
        _outToSlave.println(message);
        _outToSlave.flush();
    }
    */
    public void shutdown(boolean notify) {
        _reader.halt();
        _writer.halt();
        _writer.flushOutputQueue();
        
        try {
            //Thread.sleep(10);
            _outToSlave.close();
            //_outToSlave = null;
            
            _inFromSlave.close();
            //_inFromSlave = null;
            
            _socket.close();
            //_socket = null;

            //_reader = null;
            //_writer = null;
        } catch (IOException e) {
        }
        
        if (notify) {
            //\\System.out.println("Close socket");
//            _listener.socketClosed();

        }
    }
}

